﻿using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cs2py
{
    public class UseIronPython
    {
        public static void Run()
        {
            Console.WriteLine();
            Console.WriteLine("Iron Python");
            Console.WriteLine("********************");
            Exec_HelloWorld();
            Exec_Intergate(PysFiles.Py_intergate_numpy, 1, 10);
            Exec_Intergate(PysFiles.Py_intergate_scipy, 1, 10);
            Exec_Intergate(PysFiles.Py_intergate_sympy, 1, 10);
        }

        private static void Exec_HelloWorld()
        {
            var eng = IronPython.Hosting.Python.CreateEngine();
            var scope = eng.CreateScope();
            eng.Execute(@"
def greetings(name):
    return 'Hello ' + name.title() + '! From IronPython'
", scope);
            dynamic greetings = scope.GetVariable("greetings");
            System.Console.WriteLine(greetings("world"));
        }

        private static void Exec_Intergate(string file, float start, float stop)
        {
            var eng = IronPython.Hosting.Python.CreateEngine(AppDomain.CurrentDomain);
            try
            {
                //var code = "";
                //using (var reader = new StreamReader(File.OpenRead(file)))
                //{
                //    code = reader.ReadToEnd();
                //}
                //var src = eng.CreateScriptSourceFromFile(file);
                //src.Compile();
                //src.Execute(scope);
                var scope = eng.ExecuteFile(file);
                var name = Path.GetFileNameWithoutExtension(file);
                dynamic func = scope.GetVariable(name);
                float r = func(start, stop);
                Console.WriteLine(name + "积分结果：" + r);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
            }

        }
    }
}
